<template>
    <!-- 标签栏 -->
    <van-tabs v-model:active="StatusActive" sticky @click-tab="TabChange"  color="#fba12f" title-active-color="#fba12f" background="#f7f7f7">
        <van-tab v-for="(item, key) in StatusList" :title="item.title" :name="item.value" :key="key"></van-tab>
    </van-tabs>

    <!-- 下拉刷新 -->
    <van-pull-refresh v-model="refreshing" @refresh="OnRefresh">
        <!-- 加载列表 -->
        <van-list
            v-model:loading="loading"
            :finished="finished"
            :offset="10"
            finished-text="没有更多了"
            @load="OnLoad"
        >
            <div class="list">
                <!-- 商品卡片 -->
                <div class="item" v-for="item in list" :key="item.id">

                    <div class="header">
                        <div class="code">订单号：{{ item.code }}</div>
                        <div class="status">{{ item.status_text }}</div>
                    </div>

                    <van-card
                        :thumb="item.product.products.thumb_text"
                        @click="OnOpenProductCard(item.order_product)"
                    >
                        <template #title>
                            <div class="title">{{ item.product.products.name }}</div>
                        </template>

                        <!-- 卡片的插槽部分 -->
                        <template #desc v-if="item.product.attrs">
                            <van-tag v-for="(attr,index) in JSON.parse(item.product.attrs)" :key="index" class="tag" type="primary">{{attr.value}}</van-tag>
                        </template>

                        <!-- 卡片的插槽部分 -->
                        <template #desc v-else>
                            <van-tag class="tag" type="danger">无商品规格</van-tag>
                        </template>

                        <template #price>
                            <div class="price-box">
                                <div class="price">商品总价：￥ {{ item.product.total }}</div>
                                <div class="num">x{{ item.product.pronum }}</div>
                            </div>
                        </template>
                    </van-card>

                    <div class="footer">

                        <div class="box">

                            <div class="time">
                                下单时间：{{ item.createtime_text }}
                            </div>

                            <div class="total">
                                <div class="coupon" v-if="item.coupon">优惠：￥ {{ item.coupon_price }}</div>
                                <div>实付款：￥ {{ item.amount }}</div>
                            </div>
                        </div>

                        <div class="btn-list">
                            <!-- status = 1 仅退款 -->
                            <van-button v-if="item.status == '1'" class="button" type="danger" size="mini" @click="OnRefund1(item.id)">申请退款</van-button>
                            <van-button v-if="item.status == '2'" class="button" type="danger" size="mini" @click="OnRefund2(item.id)">申请退货退款</van-button>

                            <!-- status = 2 -->
                            <van-button v-if="item.status == '2'" class="button" type="success" size="mini" @click="OnConfirmReceive(item.id)">确认收货</van-button>
                            <van-button v-if="item.status == '2'" class="button" type="warning" size="mini" @click="ToExpress(item.id)">物流详情</van-button>

                            <!-- status = 3 已收货 -->
                            <van-button v-if="item.status == '3'" class="button" type="warning" size="mini" @click="ToOrderInfo(item.id)">立即评价</van-button>

                            <!-- 退货退款 -->
                            <van-button v-if="item.status == '-2'" class="button" type="success" size="mini">等待后台审核...</van-button>
                            <van-button v-if="item.status == '-3'" class="button" type="warning" size="mini" @click="OnBackInfo(item)">请填写退货信息</van-button>

                            <!-- 退货失败 -->
                            <van-button v-if="item.status == '-5'" class="button" type="danger" size="mini" @click="OnRefundInfo(item)">后台拒绝退货原因</van-button>

                            <van-button class="button" type="primary" size="mini" @click="ToOrderInfo(item.id)">订单详情</van-button>
                        </div>
                     </div>
                </div>
            </div>
        </van-list>
    </van-pull-refresh>

    <!-- 仅退款弹框 -->
    <van-popup v-model:show="ApplyShow1" position="bottom" round :style="{paddingBottom: '20px'}">
        <van-picker
            title="退款原因"
            :columns="RemarkList"
            @cancel="ApplyShow1 = false"
            @confirm="OnRefundApply"
        />
    </van-popup>

    <!-- 退货退款的弹框 -->
    <van-popup v-model:show="ApplyShow2" position="bottom" round>
        <van-form @submit="OnOrderApplyConfirm">
            <van-field v-model="remark" name="remark" rows="5" autosize type="textarea" maxlength="120"
                placeholder="请输入申请原因" show-word-limit :rules="[{ required: true, message: '请填写申请原因' }]" />
            <van-button square block color="linear-gradient(160deg, #0093E9 0%, #80D0C7 100%)"
                native-type="submit">提交申请</van-button>
        </van-form>
    </van-popup>

    <!-- 商品列表弹出框 -->
    <van-popup 
        v-model:show="ProductShow" 
        position="bottom" 
        round
        style="padding: 10px 0;"
    >
        <van-card v-for="item in ProductList" :thumb="item.products.thumb_text" :num="item.pronum">
            <template #title>
                <div class="title">{{item.products.name}}</div>
            </template>
    
            <!-- 卡片的插槽部分 -->
            <template #desc v-if="item.attrs">
                <van-tag v-for="(attr,index) in JSON.parse(item.attrs)" :key="index" class="tag" type="primary">{{attr.value}}</van-tag>
            </template>

            <template #desc v-else>
                <van-tag class="tag" type="danger">无规格数据</van-tag>
            </template>
    
            <template #tags>
                <div class="price">单价：￥{{item.price}}</div>
            </template>
    
            <template #price>
                <div class="price">合计：￥{{item.total}}</div>
            </template>
        </van-card>

        <div style="width:80%;margin:1em auto 0em;">
            <van-button round block type="primary" @click="ProductShow = false">关闭</van-button>
        </div>
    </van-popup>

    <!-- 退货表单信息的弹出框 -->
    <van-popup v-model:show="BackShow" position="bottom" round :style="{height: '40em'}">
        <h4 style="padding:0.5em 1em;">返厂退货信息</h4>

        <van-form>
            <van-field
                label="联系人"
                v-model="factory.contact"
                readonly
            />
            <van-field
                label="手机号"
                v-model="factory.mobile"
                readonly
            />
            <van-field
                label="返厂地址"
                v-model="factory.address"
                readonly
            />
        </van-form>

        <van-divider
            :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px' }"
        >
            分割线
        </van-divider>

        <van-form @submit="OnBackSubmit">
            <van-field
                label="物流公司"
                v-model="back.express"
                name="express"
                placeholder="请选择物流公司"
                is-link
                readonly
                @click="ExpressShow = true"
            />

            <van-field
                label="快递单号"
                v-model="back.expresscode"
                name="expresscode"
                placeholder="请输入物流单号"
                :rules="[{required: true, message: '请输入物流单号'}]"
            />

            <van-field 
                label="退货理由"
                type="textarea"
                rows="3"
                v-model="back.remark"
                placeholder="请输入退货理由"
                :rules="[
                    {required: true, message: '请输入退货理由'},
                ]"
            />

            <van-field label="上传图集">
                <template #input>
                    <van-uploader 
                        v-model="thumbs" 
                        multiple 
                        :max-count="6"
                        :readonly="back.thumbs ? true : false"
                    />
                </template>
            </van-field>

            <div style="width:50%;margin:2em auto;">
                <van-button round block color="linear-gradient(160deg, #0093E9 0%, #80D0C7 100%)" native-type="submit">提交</van-button>
            </div>
        </van-form>

    </van-popup>

    <!-- 物流公司弹出层 -->
    <van-popup v-model:show="ExpressShow" position="bottom" round>
        <van-picker 
            :columns-field-names="{text: 'name', value: 'id'}"
            :columns="ExpressData"
            v-model="ExpressActive"
            title="物流公司"
            @confirm="OnExpressConfirm"
            @cancel="ExpressShow = false"
        />
    </van-popup>

    <!-- 物流公司弹出层 -->
    <van-popup v-model:show="RefundInfoShow" position="bottom" round :style="{height: '29%'}">
        <van-field
            v-model="order.examinereason"
            rows="7"
            autosize
            type="textarea"
            colon
            placeholder="拒绝退货原因"
            readonly
        />
    </van-popup>

    <Tabbar />
</template>

<script setup>
    const { proxy } = getCurrentInstance();

    // 标签栏数据
    const StatusActive = ref('all')
    const StatusList = ref([
        { title: '全部', value: 'all' },
        { title: '已支付', value: '1' },
        { title: '已发货', value: '2' },
        { title: '已收货', value: '3' },
        { title: '已完成', value: '4' },
        { title: '退货退款', value: '-1' },
    ]);

    // 用户登录信息
    const business = proxy.$business;

    // 下拉刷新的数据
    const list = ref([]);// 数据列表
    const page = ref(1); // 分页
    const loading = ref(false);// 加载状态
    const finished = ref(false);// 是否无更多数据
    const refreshing = ref(false);// 下拉刷新

    // 申请仅退款
    const orderid = ref(0);
    const ApplyShow1 = ref(false);
    const RemarkList = ref([
        {text: '拍错了', value: '拍错了'},
        {text: '地址有误', value: '地址有误'},
        {text: '不想要了', value: '不想要了'},
        {text: '参数选错了', value: '参数选错了'},
        {text: '选择其他的', value: '选择其他的'},
    ]);

    // 退货退款 
    const ApplyShow2 = ref(false);
    const remark = ref('');

    // 商品列表弹出显示
    const ProductShow = ref(false);
    const ProductList = ref([]);

    // 退货信息弹出层
    const BackShow = ref(false);
    // 退货信息数据
    const back = ref({});
    // 退货图集
    const thumbs = ref([]);

    // 厂家信息
    const factory = ref({});

    // 物流数据
    const ExpressData = ref([]);

    // 订单信息
    const order = ref({});

    // 物流公司弹出层
    const ExpressShow = ref(false);
    // 当前退货选中物流
    const ExpressActive = ref([0]);

    // 后台拒绝退货
    const RefundInfoShow = ref(false);

    // 标签栏切换
    const TabChange = async ({ name }) =>
    {
        OnRefresh();
    }

    // 下拉刷新
    const OnRefresh = async () =>
    {
        // 清空查询参数
        page.value = 1;
        list.value = [];
        finished.value = false;
        loading.value = true;
        refreshing.value === true

        setTimeout(OnLoad,1500);
    }

    // 加载数据方法 查询订单数据
    const OnLoad = async () =>
    {
        // 如果等于true说明当前进行下拉刷新
        if(refreshing.value === true)
        {
            // 结束下拉刷新
            refreshing.value = false;
        }

        // 组装数据
        let params = {
            page:page.value,
            busid:business.value.id,
            status:StatusActive.value
        }

        // 发起请求
        let result = await proxy.$POST({
            url:'/order/index',
            params
        })

        // 请求发送完毕后，加载状态也就完毕了
        loading.value = false;

        if(result.code === 1)
        {
            // 合并数组
            list.value = list.value.concat(result.data.list);
            let count = result.data.count;

            list.value.map(item => {

                // 从订单商品里取第一个商品渲染到列表
                item.product = item.order_product[0] ?? null;

                // 如果有使用优惠券
                if(item.coupon)
                {
                    // 购买的商品总价
                    let amount = 0;

                    // 循环计算
                    item.order_product.map(product => {
                        amount += parseFloat(product.total);
                    })

                    // 优惠价格
                    item.coupon_price = (amount - parseFloat(item.amount)).toFixed(2);
                }
            });

            // 如果没有更多数据了，就说明已经加载到底了
            if(list.value.length === count)
            {
                finished.value = true;

                return false;
            }

            page.value = page.value + 1;
        }else
        {
            finished.value = true;

            proxy.$fail(result.msg);
        }
    }

    // 点击card组件可以查看当前订单购买的商品
    const OnOpenProductCard = (item) =>
    {
        ProductList.value = item;

        ProductShow.value = true;
    }

    // 仅退款
    const OnRefund1 = (id) =>
    {
        proxy.$confirm({
            title: '申请退款',
            message: '是否确认申请该订单退款?'
        }).then(async () => {
            ApplyShow1.value = true;
            orderid.value = id;
        }).catch(err => {});
    }

    // 确认收货
    const OnConfirmReceive = (orderid) =>
    {
        proxy.$confirm({
            title: '确认收货',
            message: '是否确认收货?',
        }).then(async () =>
        {
            let result = await proxy.$POST({
                url: '/order/receive',
                params: {
                    orderid,
                    busid:business.value.id
                }
            })

            if(result.code === 1)
            {
                proxy.$success(result.msg);

                OnRefresh();
            }else
            {
                proxy.$fail(result.msg);
            }
        }).catch(err => {})
    }

    // 退货退款
    const OnRefund2 = (id) =>
    {
        proxy.$confirm({
            title: '申请退货退款',
            message: '是否确认申请该订单退货退款?'
        }).then(async () => {
            ApplyShow2.value = true
            orderid.value = id
        }).catch(err => {});
    }

    // 提交退货退款的原因
    const OnOrderApplyConfirm = async () =>
    {
        ApplyShow2.value = false;

        //组装数据
        let params = {
            orderid:orderid.value,
            refundreason: remark.value,
            busid:business.value.id
        }

        let result = await proxy.$POST({
            url: '/order/back',
            params
        });

        if(result.code === 1)
        {
            proxy.$success({
                message:result.msg,
                onClose:() =>
                {
                    // 把原因清空
                    remark.value = '';
                    
                    // 重新刷新列表
                    OnRefresh();

                }
            });
        }else
        {
            proxy.$fail(result.msg);
        }
       
    }

    // 申请仅退款
    const OnRefundApply = async ({selectedValues}) =>
    {
        // 退款的原因
        let refundreason = selectedValues[0] ?? '拍错了';

        // 组装数据
        let params = {
            orderid:orderid.value,
            refundreason:refundreason,
            busid:business.value.id
        }

        // 发起请求
        let result = await proxy.$POST({
            url:'/order/refund',
            params
        });

        ApplyShow1.value = false;

        if(result.code === 1)
        {
            proxy.$success({
                message:result.msg,
                onClose:() =>
                {
                    OnRefresh();
                }
            });
        }else
        {
            proxy.$fail(result.msg);
        }
    }

    // 填写退货详情
    const OnBackInfo = async (item) =>
    {
        BackShow.value = true;

        // 保留订单信息
        order.value = item;
        
        //获取退货返厂的信息
        let result = await proxy.$POST({url: '/order/factory',params:{orderid:item.id}})

        factory.value = result.data.factory;
        ExpressData.value = result.data.ExpressData;

        if(result.data.back && Object.getOwnPropertyNames(result.data.back).length > 0)
        {
            back.value.expressid = result.data.back.expressid;
            back.value.express = result.data.back.express_text;
            back.value.expresscode = result.data.back.expresscode;
            back.value.remark = result.data.back.remark;
            back.value.thumbs = result.data.back.thumbs;
            back.value.thumbs_cdn = result.data.back.thumbs_cdn;
            
            if(result.data.back.thumbs)
            {
                thumbs.value = [];

                result.data.back.thumbs_cdn.map(thumb => {
                    thumbs.value.push({
                        url:thumb
                    });
                });
            }

            ExpressActive.value = [back.value.expressid];
        }

    }

    // 提交退货信息
    const OnBackSubmit = async () =>
    {
        let params = {
            orderid: order.value.id,
            busid: order.value.busid,
            expressid: back.value.expressid, //物流公司的外键
            expresscode: back.value.expresscode, //物流单号
            remark:back.value.remark,
            busid:business.value.id
        }

        // 是否有提交图片
        if(thumbs.value.length > 0)
        {
            // 定义一个空数组存放用户提交的退货图片
            let list = [];

            // 图片追加到数组中
            thumbs.value.map(item => (item.file && list.push(item.file)));
            
            params.thumbs = list;
        }

        let result = await proxy.$UPLOAD({
            url:'/order/refunds',
            params
        })
        
        if(result.code === 1)
        {
            BackShow.value = false;

            proxy.$success(result.msg);
        }else{
            proxy.$fail(result.msg);
        }
    }

    // 选择物流公司
    const OnExpressConfirm = ({selectedOptions}) =>
    {
        ExpressShow.value = false;

        back.value.expressid = selectedOptions[0].id;
        back.value.express = selectedOptions[0].name;
    }

    // 显示后台拒绝退货原因
    const OnRefundInfo = (item) =>
    {
        RefundInfoShow.value = true;

        order.value = item;
    }

    // 跳转订单详情
    const ToOrderInfo = (orderid) => proxy.$router.push({path:'/order/info',query:{orderid}});

    // 跳转物流详情
    const ToExpress = (orderid) => proxy.$router.push({path:'/order/express',query:{orderid}});
</script>


<style scoped>
    @import url('/assets/css/OrderIndex.css');
</style>